#!/usr/bin/env ruby

#  Permission is hereby granted, free of charge, to any person obtaining a
#  copy of this software and associated documentation files (the "Software"),
#  to deal in the Software without restriction, including without limitation
#  the rights to use, copy, modify, merge, publish, distribute, sublicense,
#  and/or sell copies of the Software, and to permit persons to whom the
#  Software is furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.
#

require 'optparse'
require File.join(File.dirname(__FILE__), '../Spec/vectors', 'vectorparser')

@test_files = ["v3/kdf", "v3/password", "v3/key", 
               "v2/kdf", "v2/password",
               "v1/kdf", "v1/password",
              ]

@options = {}

# Returns the text for an NSDictionary assignment from a hash
def DictionaryForHash(hash)
  "[\n" + hash.collect { |key, value| %Q(    "#{key}": "#{value}") }.join(",\n") + "]"
end

# Output the file header to output stream
def outputHeader(output)
  output << <<-HEADER
// Automatically Generated by GenVectorTests
import XCTest

class GeneratedVectorTests: XCTestCase {
HEADER
end

# Output the tests for a given filename to the output stream
def outputTestsForFile(output, name)
  name_identifier = name.gsub('/', '_')
  VectorParser.new(@options[:vector_directory] + '/' + name).vectors.each do |vector|
    output << <<-TEST_CASE

func test_#{name_identifier}_#{vector["title"].gsub(/[ ()-]+/, '_')}() {
  verify_#{name_identifier}(#{DictionaryForHash(vector)})
}

TEST_CASE
  end
end

# Output the footer to the output stream
def outputFooter(output)
    output<< <<-FOOTER
}
FOOTER
end

###################
### MAIN
###################
opt_parser = OptionParser.new do |opt|
  opt.banner = "Usage: GenVectorTest -o VectorTests.m <vector_directory>"
  opt.separator  ""
  opt.on("-o","--output PATH","path to output code") do |output_path|
    @options[:output_path] = output_path
  end
end

opt_parser.parse!

raise OptionParser::MissingArgument if @options[:output_path].nil?
raise OptionParser::MissingArgument if ARGV.length != 1

@options[:vector_directory] = ARGV[0]

File.open(@options[:output_path], "w") do |output|
  outputHeader(output)
  @test_files.each do |file|
    outputTestsForFile(output, file)
  end
  outputFooter(output)
end
